<template>
    <a-modal :visible="visible" @update:visible="emit('update:visible', $event)" :title="modelData.name"
        @cancel="handleCancel" width="800px" class="ai-model-dialog" :bodyStyle="{ padding: '0' }" :footer="null">
        <div class="model-details">
            <div class="model-content">
                <div class="chat-container">
                    <div class="chat-messages" ref="messagesContainer">
                        <div v-for="(message, index) in messages" :key="index"
                            :class="['message', message.type === 'user' ? 'message-user' : 'message-ai']">
                            <div class="message-avatar">
                                <UserOutlined v-if="message.type === 'user'" />
                                <RobotOutlined v-else />
                            </div>
                            <div class="message-content">
                                 <!-- 思考过程（带标签） -->
                                <div class="thinking-process" v-if="message.thinking">
                                    <span class="process-label">[思考过程]</span>
                                    <span>{{ message.thinking }}</span>
                                </div>
                                <!-- 输出内容 -->
                                <div class="message-text" v-if="message.output">
                                    {{ message.output }}
                                </div>

                                <div class="message-time">{{ message.time }}</div>
                            </div>
                        </div>
                        <!-- 错误提示 -->
                        <div v-if="error" class="error-message">
                            {{ error }}
                        </div>
                    </div>
                    <div class="chat-input">
                        <a-input-search v-model:value="inputMessage" placeholder="请输入您的问题..." enter-button="发送"
                            size="large" @search="sendMessage" :loading="loading" :disabled="loading"
                            @keyup.enter="handleEnter">
                            <template #enterButton>
                                <a-button type="primary" :loading="loading" :disabled="loading">
                                    <template #icon>
                                        <SendOutlined />
                                    </template>
                                    发送
                                </a-button>
                            </template>
                        </a-input-search>
                    </div>
                </div>
            </div>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref } from 'vue'
import { UserOutlined, RobotOutlined, SendOutlined } from '@ant-design/icons-vue'
import { queryModel } from '@/utils/aiModel'

// 定义消息类型（新增thinking和output字段）
interface Message {
    type: 'user' | 'ai'
    content?: string // 原始内容（保留用于解析）
    output?: string // 最终输出内容（标签外部分）
    thinking?: string // 思考过程（标签内部分）
    time: string
}

const props = defineProps({
    visible: {
        type: Boolean,
        required: true
    },
    modelData: {
        type: Object,
        required: true,
        default: () => ({
            name: '',
            description: '',
            version: '',
            type: '',
            url: '' // 确保父组件传递url
        })
    }
})

const emit = defineEmits(['update:visible'])
const inputMessage = ref('') // 明确类型为string
const loading = ref(false)
const messagesContainer = ref<HTMLElement | null>(null)
const error = ref('')

const messages = ref<Message[]>([
    {
        type: 'ai',
        output: '你好！我是AI助手，很高兴为您服务。请问有什么我可以帮助您的吗？',
        time: new Date().toLocaleTimeString()
    }
])

const scrollToBottom = () => {
    if (messagesContainer.value) {
        setTimeout(() => {
            messagesContainer.value!.scrollTop = messagesContainer.value!.scrollHeight
        }, 100)
    }
}

// 新增回车事件处理函数（避免与@search重复触发）
const handleEnter = () => {
    if (loading.value) return // 加载中不处理回车
    sendMessage() // 统一调用发送逻辑
}

// 重新编写的解析函数
const parseResponse = (content: string): { output: string; thinking?: string } => {
    const tagRegex = /<think>([\s\S]*?)<\/think>/;
    const match = content.match(tagRegex);

    if (match) {
        const thinking = match[1].trim();
        const output = content.replace(match[0], '').trim();
        return { output, thinking };
    } else {
        return { output: content.trim() };
    }
}

const sendMessage = async () => {
    if (loading.value) return // 核心：加载中直接返回，防止重复发送

    const originalValue = inputMessage.value
    const trimmedValue = originalValue.trim()

    if (!trimmedValue) {
        error.value = '输入内容不能为空或仅包含空格'
        return
    }

    error.value = ''
    loading.value = true // 立即设置加载状态，防止快速点击

    try {
        const userMessage: Message = {
            type: 'user',
            content: originalValue,
            output: originalValue, // 用户消息无需解析
            time: new Date().toLocaleTimeString()
        }
        messages.value.push(userMessage)
        inputMessage.value = ''
        scrollToBottom()

        const rawResponse = await queryModel(
            props.modelData.url,
            trimmedValue,
            100000,
            0.7,
            props.modelData.name
        )
        const content = rawResponse.content || ''
        const { output, thinking } = parseResponse(content)

        const aiMessage: Message = {
            type: 'ai',
            output,
            thinking,
            time: new Date().toLocaleTimeString()
        }
        inputMessage.value = ''
        messages.value.push(aiMessage)
        scrollToBottom()
    } catch (e) {
        error.value = (e as Error).message
    } finally {
        loading.value = false // 请求完成后释放加载状态
    }
}

const handleCancel = () => {
    emit('update:visible', false)
    error.value = ''
    inputMessage.value = ''
    messages.value = [
        {
            type: 'ai',
            output: '你好！我是AI助手，很高兴为您服务。请问有什么我可以帮助您的吗？',
            time: new Date().toLocaleTimeString()
        }
    ]
}
</script>

<style scoped>
.ai-model-dialog :deep(.ant-modal-content) {
    border-radius: 16px;
    overflow: hidden;
}

.model-details {
    background: #f8f9fa;
}

.model-content {
    display: flex;
    gap: 24px;
    padding: 24px;
}

.chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: white;
    border-radius: 12px;
    overflow: hidden;
    height: 600px;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    scroll-behavior: smooth;
}

.message {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    opacity: 0;
    transform: translateY(20px);
    animation: messageAppear 0.3s ease forwards;
}

@keyframes messageAppear {
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.message-user {
    flex-direction: row-reverse;
}

.message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f0f2f5;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.message-user .message-avatar {
    background: #e6f7ff;
}

.message-ai .message-avatar {
    background: #f6ffed;
}

.message-content {
    max-width: 70%;
}

.message-text {
    padding: 12px 16px;
    border-radius: 12px;
    background: #f0f2f5;
    font-size: 14px;
    line-height: 1.6;
    word-break: break-word;
}

.message-user .message-text {
    background: #1890ff;
    color: white;
}

.message-time {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
    margin-top: 4px;
    text-align: right;
}

.message-user .message-time {
    text-align: left;
}

.chat-input {
    padding: 16px;
    background: white;
    border-top: 1px solid #f0f0f0;
}

.chat-input :deep(.ant-input-search) {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}

.chat-input :deep(.ant-input) {
    border-radius: 8px 0 0 8px;
    padding: 8px 16px;
}

.chat-input :deep(.ant-input-search-button) {
    height: 40px;
    border-radius: 0 8px 8px 0;
    width: 100px;
}

.chat-input :deep(.anticon) {
    font-size: 16px;
}

.error-message {
    margin: 10px;
    padding: 12px;
    background-color: #fff2f0;
    border: 1px solid #ffccc7;
    border-radius: 8px;
    color: #ff4d4f;
    font-size: 14px;
    text-align: center;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.message-text {
    white-space: pre-wrap;
    word-break: break-word;
}

.thinking-process {
    margin-top: 12px;
    padding: 8px 16px;
    border-radius: 8px;
    background: #f8f9fa;
    font-size: 13px;
    color: rgba(0, 0, 0, 0.65);
    white-space: pre-wrap;
}

.process-label {
    font-style: normal;
    color: #666;
    margin-right: 8px;
    font-weight: 500;
}
</style>